package com.apes.scm.masterdata.frame.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.frame.model.PurchaseRanges;
import com.apes.scm.masterdata.frame.repository.PurchaseRangesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：采购范围
 */
@Service("purchaseRangesService")
public class PurchaseRangesService extends DomainService {

    @Autowired
    public PurchaseRangesRepository purchaseRangesRepository;

    /**
     * 功能：采购范围创建
     * @param request
     * @return
     */
    public PurchaseRanges save(SimpleRequest request){
        PurchaseRanges purchaseRanges = request.getO(PurchaseRanges.class);
        return purchaseRangesRepository.saveAndFlush(purchaseRanges);
    }

    public void checkData(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        PurchaseRanges oldPurchaseRanges = purchaseRangesRepository.findOne(id);
        if (oldPurchaseRanges == null) throw new RuntimeException("采购范围【" + id + "】在系统中不存在。");
        if (oldPurchaseRanges.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }

    public PurchaseRanges update(SimpleRequest request){
        checkData(request);

        PurchaseRanges purchaseRanges = request.getO(PurchaseRanges.class);
        return purchaseRangesRepository.saveAndFlush(purchaseRanges);
    }

    public String delete(SimpleRequest request){
        checkData(request);

        PurchaseRanges purchaseRanges = request.getO(PurchaseRanges.class);
        purchaseRangesRepository.delete(purchaseRanges);
        return "删除成功！";
    }

    /**
     * 功能：查询所有的采购范围
     * @param request
     * @return
     */
    public Page<PurchaseRanges> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return purchaseRangesRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

}
